package math

import (
	"strconv"
	"strings"
)

type Decimal struct {
	neg  bool   //负数
	ints []byte //整数
	decs []byte //小数
}

func (x *Decimal) FromString(s string) bool {
	neg := false
	if len(s) > 0 {
		if s[0] == '-' {
			neg = true
			s = s[1:]
		} else if s[0] == '+' {
			s = s[1:]
		}
		if len(s) == 0 {
			return false
		}
	}
	ints, decs, ok := strings.Cut(s, ".")
	for _, b := range ints {
		if b < '0' || b > '9' {
			return false
		}
	}
	if ok {
		for _, b := range decs {
			if b < '0' || b > '9' {
				return false
			}
		}
	}
	x.neg = neg
	x.ints = []byte(ints)
	if ok {
		x.decs = []byte(decs)
	} else {
		x.decs = []byte{}
	}
	return true
}

func (x Decimal) ToString() string {
	s := ""
	if x.neg {
		s = "-"
	}
	s += string(x.ints)
	if len(x.decs) > 0 {
		s += "." + string(x.decs)
	}
	return s
}

func (x Decimal) ToFloat() float64 {
	s := x.ToString()
	f, _ := strconv.ParseFloat(s, 64)
	return f
}

// 保留小数
func (x *Decimal) Reserved(n int) {
	if len(x.decs) > n {
		x.decs = x.decs[:n]
	} else {
		n = n - len(x.decs)
		for n > 0 {
			n--
			x.decs = append(x.decs, '0')
		}
	}
}
